import axios from 'axios';
import type { AxiosRequestConfig } from 'axios';
// import { MessageBox, Message } from 'element-ui'
// import store from '@/store'
import { getToken, removeToken } from '@/utils/cookies';
import { debounce } from './index';
import i18n from '@/i18n';

const { t } = i18n.global;

// create an axios instance
const service = axios.create({
	baseURL: import.meta.env.VITE_BASE_API, // url = base url + request url
	// withCredentials: true, // 跨域请求发送cookie
	timeout: 20 * 1e3, // request timeout
});

// request interceptor
service.interceptors.request.use(
	config => {
		// do something before request is sent
		const token = getToken();
		if (token) {
			config.headers['token'] = token;
			config.headers['lang'] = 'zh';
		}
		return config;
	},
	error => {
		const Message = window['$message'];
		console.log(error); // for debug
		Message.error(error);
		return Promise.reject(error);
	}
);

// response interceptor
service.interceptors.response.use(
	response => {
		const res = response.data;
		const Message = window['$message'];

		if (res.code !== 1) {
			if (res.code === 1006 || res.code === 1003) {
				loginTimeout();
				return Promise.reject(res.message);
			} else {
				Message.error(res.message || 'Error');
			}
			return Promise.reject(new Error(res.message || 'Error'));
		} else {
			return res;
		}
	},
	error => {
		const Message = window['$message'];
		console.log('err' + error); // for debug
		if (error.message.includes('timeout')) {
			requestTimeout();
		}
		httpStatusDel(error);
		return Promise.reject(error);
	}
);

const http = <T>(config: AxiosRequestConfig): Promise<ResponseData<T>> => {
	return service.request(config);
};

/** 请求超时 */
const requestTimeout = debounce(() => timeout(), 1000);
function timeout() {
	const Message = window['$message'];
	Message.error(t('msg.reqTimeout'));
}

/** 登录过期 */
const loginTimeout = debounce(() => loginExpired(), 1000);
function loginExpired() {
	const Message = window['$message'];
	Message.warning(t('msg.loginExpires'));
	removeToken();
	window.location.href = '#/login';
}

/** 错误码处理 */
const httpStatusDel = debounce(error => statusDel(error), 2000);
function statusDel(error) {
	const Message = window['$message'];
	switch (error.response.status) {
		case 500:
			Message.error(t('msg.serverErr'));
			break;
		default:
			Message.error(error.message);
			break;
	}
}

export default http;
